#include "loginwidget.h"
#include "ui_loginwidget.h"
#include"config.h"
#include<QString>

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    keyboard = new KeyBoard();

    ui->lineEdit_name->installEventFilter(keyboard);
    ui->lineEdit_pw->installEventFilter(keyboard);
    ui->lineEdit_pw->setText("");
    ui->lineEdit_name->setText("");
}
LoginWidget::~LoginWidget(){
    delete ui;
}

void LoginWidget::getSocket(){
    socket = new QTcpSocket;
    connect(socket,&QTcpSocket::readyRead,this,&LoginWidget::recv_data);
    connect(socket,&QTcpSocket::connected,this,&LoginWidget::connectSuccess);
    socket->connectToHost(SOCKET_SERVER_ADDRESS,7777);
}
void LoginWidget::on_pushButton_login_clicked()
{
    QString name = ui->lineEdit_name->text(); // 将用户名和密码发送给服务器进行注册
    QString passwd = ui->lineEdit_pw->text();// 接收服务器返回的注册结果，并根据结果进行相应的处理
    if(QString::compare(name,"")==0)
    {
        return;
    }
    getSocket();
    char buf[20];char buf_name[20];char buf_passwd[20];
    strcpy(buf,"login");
    strcpy(buf_name,name.toLatin1().data());
    strcpy(buf_passwd,passwd.toLatin1().data());
    qDebug()<<socket->write(buf,20);
    socket->write(buf_name, 20);
    socket->write(buf_passwd, 20);
    qDebug()<<"post";
}




void LoginWidget::recv_data()
{
    char buf[20];
    socket->read(buf, sizeof(buf)); // 读取服务器返回的数据
    if(strcmp(buf, "200") == 0) // 如果返回的数据为"200"
    {

        qDebug()<<"login to main";
        goToMain();
    }
    else
    {
        ui->lineEdit_recv->setText(buf); // 在界面上显示返回的数据
        socket->close();
    }
    ui->lineEdit_pw->setText("");
}

void LoginWidget::on_pushButton_register_clicked()
{
    QString name = ui->lineEdit_name->text(); // 将用户名和密码发送给服务器进行注册
    QString passwd = ui->lineEdit_pw->text();// 接收服务器返回的注册结果，并根据结果进行相应的处理
    if(QString::compare(name,"")==0)
    {
        return;
    }
    getSocket();
    char buf[20]="register";
    socket->write(buf,sizeof(buf));
    char buf_name[20], buf_passwd[20];
    strcpy(buf_name, name.toLatin1().data()); // 将QString类型的用户名转换为char数组
    strcpy(buf_passwd, passwd.toLatin1().data()); // 将QString类型的密码转换为char数组
    // 发送用户名和密码给服务器
    socket->write(buf_name, sizeof(buf_name));
    socket->write(buf_passwd, sizeof(buf_passwd));
    qDebug() << buf_name<<buf_passwd;
}
void LoginWidget::goToMain()
{
    mainWidget = new MainWidget(this);
    mainWidget->show();
    socket->close();
    this->close();
}

void LoginWidget::connectSuccess()
{
    qDebug() << "客户端连接成功";
}

